<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background-color: skyblue;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <div class="box" id="box"></div>
    <script>
      var box = document.getElementById('box')
      // 第一步：给盒子绑定鼠标按下事件
      box.addEventListener('mousedown', function (event) {
        // 按下的时候，获取当前光标距离盒子顶部和左侧的距离
        var downX = event.clientX - box.getBoundingClientRect().left
        var downY = event.clientY - box.getBoundingClientRect().top
        console.log('down')
        // 第二步：给文档document绑定移动事件
        function move(event) {
          // 获取基于浏览器的xy坐标
          var moveX = event.clientX
          var moveY = event.clientY
          // 把xy赋值给盒子的left和top偏移量
          box.style.left = moveX - downX + 'px'
          box.style.top = moveY - downY + 'px'
          console.log('move', moveX, moveY)
        }
        document.addEventListener('mousemove', move)
        // 第三步：给盒子绑定鼠标抬起事件，要解绑文档的移动事件
        box.addEventListener('mouseup', function () {
          console.log('up')
          document.removeEventListener('mousemove', move)
        })
      })
    </script>
  </body>
</html>
